package chapter01.part3;

import chapter01.part1.CountWordByLength;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Stream;

/**
 * 使用 filter() & map() & flatmap()
 * 
 * @author insight 
 * @since 2021/7/19
 */
public class FilterMapFlatmap {
    public static void main(String[] args) {
        // 匹配条件的流
        List<String> words = CountWordByLength.getWordList();
        Stream<String> length =
                words.stream().filter(w -> w.length() > 10);

        // 转换值的流
        Stream<String> lower = words.stream().map(String::toLowerCase);
        Stream<String> subs = words.stream().map(s -> s.substring(0, 3));

        // 在 map 上对每一个元素使用函数
        Stream<Stream<String>> streams =
                words.stream().map(FilterMapFlatmap::codePoints);

        // 可以使用 flatmap 摊平
        Stream<String> stream =
                words.stream().flatMap(FilterMapFlatmap::codePoints);
    }

    public static Stream<String> codePoints(String s) {
        List<String> list = new ArrayList<>();

        int i = 0;
        while (i < s.length()) {
            int j = s.offsetByCodePoints(i, 1);
            list.add(s.substring(i, j));
            i = j;
        }

        return list.stream();
    }
}